package com.chengyu.core.controller.common;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.DesensitizedUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.chengyu.core.controller.UserBaseController;
import com.chengyu.core.domain.CommonConstant;
import com.chengyu.core.domain.enums.ConfigEnums;
import com.chengyu.core.domain.enums.MemberTypes;
import com.chengyu.core.entity.CommonResult;
import com.chengyu.core.exception.ServiceException;
import com.chengyu.core.mapper.UmsMemberMapper;
import com.chengyu.core.model.SysInviteCode;
import com.chengyu.core.model.SysWeixinConfig;
import com.chengyu.core.model.UmsMember;
import com.chengyu.core.model.UmsMemberExample;
import com.chengyu.core.service.member.MemberImeIdService;
import com.chengyu.core.service.system.ConfigService;
import com.chengyu.core.service.system.SysInviteCodeService;
import com.chengyu.core.service.system.VerifyCodeService;
import com.chengyu.core.service.system.WeixinConfigService;
import com.chengyu.core.util.weixin.GZHWeixin;
import com.chengyu.core.util.weixin.HttpClientUtil;
import com.chengyu.core.util.weixin.WechatUtil;
import com.chengyu.core.utils.StringUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @title  公共管理类
 * @author LeGreen
 * @date   2021/1/8
 */
@Log4j2
@Api(tags = "公共管理类")
@Controller
@RequestMapping("/common")
public class CommonController extends UserBaseController {
	@Autowired
	private WeixinConfigService weixinService;
	@Autowired
	private UmsMemberMapper memberMapper;
	@Autowired
	private ConfigService configService;
	@Autowired
	private VerifyCodeService verifyCodeService;
	@Autowired
	private SysInviteCodeService inviteCodeService;
	@Autowired
	private MemberImeIdService memberImeIdService;
	@RequestMapping("/gzh/answer")
	@ResponseBody
	public String answer(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String echostr = request.getParameter("echostr");
		if (StringUtils.isNotBlank(echostr)) {
			return echostr;
		}

		String success = "success";
		InputStream inStream = request.getInputStream();
		int _buffer_size = 1024;
		if (inStream != null) {
			ByteArrayOutputStream outStream = new ByteArrayOutputStream();
			byte[] tempBytes = new byte[_buffer_size];
			int count = -1;
			while ((count = inStream.read(tempBytes, 0, _buffer_size)) != -1) {
				outStream.write(tempBytes, 0, count);
			}
			tempBytes = null;
			outStream.flush();
			//将流转换成字符串
			String result = new String(outStream.toByteArray(), "UTF-8");
			if (StringUtils.isBlank(result)) {
				return success;
			}
			System.out.println("微信公众号被动消息回复:" + result);
			WeixinMsgResponse msgResponse = WechatUtil.xmlToBean(result, WeixinMsgResponse.class);
			if (msgResponse == null) {
				return success;
			}
			String kefuWeixin = configService.getValueByNid("fs_kefu_wx");
			if("subscribe".equals(msgResponse.getEvent())){
				log.info("是否进入关注公众号");
				return "<xml>\n" +
						"  <ToUserName><![CDATA["+msgResponse.getFromUserName()+"]]></ToUserName>\n" +
						"  <FromUserName><![CDATA["+msgResponse.getToUserName()+"]]></FromUserName>\n" +
						"  <CreateTime>"+DateUtil.currentSeconds()+"</CreateTime>\n" +
						"  <MsgType><![CDATA[text]]></MsgType>\n" +
						"  <Content><![CDATA[感谢您的关注,\n" +
						"绑定账号请直接回复平台【手机号】,例: 13444555666 \n" +
						"操作中有任何问题请及时联系客服微信【"+kefuWeixin+"】。" +
						"]]></Content>\n" +
						"</xml>";
			}
			if (StringUtils.isBlank(msgResponse.getContent())) {
				return success;
			}
			if("我要解绑".equals(msgResponse.getContent())){
				UmsMemberExample example = new UmsMemberExample();
				example.createCriteria().andGzhOpenIdEqualTo(msgResponse.getFromUserName());

				UmsMember updateMember = new UmsMember();
				updateMember.setGzhOpenId("");
				updateMember.setGzhFocusStatus(CommonConstant.NO_INT);
				memberMapper.updateByExampleSelective(updateMember, example);

				if(StringUtils.isNotBlank(kefuWeixin)){
					return "<xml>\n" +
							"  <ToUserName><![CDATA["+msgResponse.getFromUserName()+"]]></ToUserName>\n" +
							"  <FromUserName><![CDATA["+msgResponse.getToUserName()+"]]></FromUserName>\n" +
							"  <CreateTime>"+DateUtil.currentSeconds()+"</CreateTime>\n" +
							"  <MsgType><![CDATA[text]]></MsgType>\n" +
							"  <Content><![CDATA[欢迎来到我们的大家庭，\n" +
							"您的微信已解绑成功, \n" +
							"操作中有任何问题请及时联系客服【"+kefuWeixin+"】。" +
							"]]></Content>\n" +
							"</xml>";
				}else{
					return "<xml>\n" +
							"  <ToUserName><![CDATA["+msgResponse.getFromUserName()+"]]></ToUserName>\n" +
							"  <FromUserName><![CDATA["+msgResponse.getToUserName()+"]]></FromUserName>\n" +
							"  <CreateTime>"+DateUtil.currentSeconds()+"</CreateTime>\n" +
							"  <MsgType><![CDATA[text]]></MsgType>\n" +
							"  <Content><![CDATA[欢迎来到我们的大家庭，\n" +
							"您的微信已解绑成功, \n" +
							"操作中有任何问题请及时联系客服。]]></Content>\n" +
							"</xml>";
				}
			}else{
				//判断该微信号是否已绑定
				UmsMember wxMember = memberService.getMemberByParams(msgResponse.getFromUserName(), MemberTypes.GZH_OPEN_ID);
				if(wxMember != null){
					if(StringUtils.isNotBlank(kefuWeixin)){
						return "<xml>\n" +
								"  <ToUserName><![CDATA["+msgResponse.getFromUserName()+"]]></ToUserName>\n" +
								"  <FromUserName><![CDATA["+msgResponse.getToUserName()+"]]></FromUserName>\n" +
								"  <CreateTime>"+DateUtil.currentSeconds()+"</CreateTime>\n" +
								"  <MsgType><![CDATA[text]]></MsgType>\n" +
								"  <Content><![CDATA[欢迎来到我们的大家庭，\n" +
								"您的微信已绑定了账号："+wxMember.getCode()+",\n" +
								"不能重复绑定，\n" +
								"如需解绑请发送'我要解绑'。\n" +
								"操作中有任何问题请及时联系客服【"+kefuWeixin+"】。" +
								"]]></Content>\n" +
								"</xml>";
					}else{
						return "<xml>\n" +
								"  <ToUserName><![CDATA["+msgResponse.getFromUserName()+"]]></ToUserName>\n" +
								"  <FromUserName><![CDATA["+msgResponse.getToUserName()+"]]></FromUserName>\n" +
								"  <CreateTime>"+DateUtil.currentSeconds()+"</CreateTime>\n" +
								"  <MsgType><![CDATA[text]]></MsgType>\n" +
								"  <Content><![CDATA[欢迎来到我们的大家庭，\n" +
								"您的微信已绑定了账号："+wxMember.getCode()+",\n" +
								"不能重复绑定，\n" +
								"如需解绑请发送'我要解绑'。\n" +
								"操作中有任何问题请及时联系客服。]]></Content>\n" +
								"</xml>";
					}
				}
				UmsMember haveMember = memberService.getMemberByParams(msgResponse.getContent(), MemberTypes.CODE);
				if(haveMember != null){
					UmsMember updateMember = new UmsMember();
					updateMember.setId(haveMember.getId());
					updateMember.setGzhOpenId(msgResponse.getFromUserName());
					updateMember.setGzhFocusStatus(CommonConstant.YES_INT);
					memberService.updateMember(updateMember);

					if(StringUtils.isNotBlank(kefuWeixin)){
						return "<xml>\n" +
								"  <ToUserName><![CDATA["+msgResponse.getFromUserName()+"]]></ToUserName>\n" +
								"  <FromUserName><![CDATA["+msgResponse.getToUserName()+"]]></FromUserName>\n" +
								"  <CreateTime>"+DateUtil.currentSeconds()+"</CreateTime>\n" +
								"  <MsgType><![CDATA[text]]></MsgType>\n" +
								"  <Content><![CDATA[欢迎来到我们的大家庭，\n" +
								"您的用户名是："+haveMember.getCode()+",\n" +
								"注意保管好您的账户信息，\n" +
								"密码打死也不要告诉任何人。\n" +
								"操作中有任何问题请及时联系客服【"+kefuWeixin+"】。" +
								"]]></Content>\n" +
								"</xml>";
					}else{
						return "<xml>\n" +
								"  <ToUserName><![CDATA["+msgResponse.getFromUserName()+"]]></ToUserName>\n" +
								"  <FromUserName><![CDATA["+msgResponse.getToUserName()+"]]></FromUserName>\n" +
								"  <CreateTime>"+DateUtil.currentSeconds()+"</CreateTime>\n" +
								"  <MsgType><![CDATA[text]]></MsgType>\n" +
								"  <Content><![CDATA[欢迎来到我们的大家庭，\n" +
								"您的用户名是："+haveMember.getCode()+",\n" +
								"注意保管好您的账户信息，\n" +
								"密码打死也不要告诉任何人。\n" +
								"操作中有任何问题请及时联系客服。]]></Content>\n" +
								"</xml>";
					}
				}
			}
		}

		return success;
	}



	@RequestMapping(value={"/veritySmsCode"}, method= RequestMethod.POST)
	@ResponseBody
	public CommonResult veritySmsCode(String phone,String code) throws Exception {
			verifyCodeService.validateCode(phone, code);
		return CommonResult.success(null);
	}

	@RequestMapping(value={"/gzh/getAccessToken"}, method= RequestMethod.POST)
	@ResponseBody
	public CommonResult getAccessToken(String code) throws Exception {
		GZHWeixin gzhWeixin = new GZHWeixin();
		SysWeixinConfig config = weixinService.getWeixinConfig();
		String userInfo = "";
		String accessUrl = WechatUtil.AUTH2_URL
				.replace("APPID", config.getGzhAppId())
				.replace("SECRET", config.getGzhSecret())
				.replace("CODE", code);
		String accessTokenStr = HttpClientUtil.httpGet(accessUrl);
		JSONObject jsonObject = JSON.parseObject(accessTokenStr);
		if (jsonObject.get("errcode") != null){
			System.out.println(jsonObject.get("errcode").toString() + ":" + jsonObject.get("errmsg"));
			gzhWeixin.setErrorCode(jsonObject.get("errcode").toString());
			return CommonResult.success(gzhWeixin);
		}


		String accessToken = jsonObject.getString("access_token");
		String openId = jsonObject.getString("openid");
		//根据openId和access_token获取用户头像和昵称
		String accessUrl2 = String.format("https://api.weixin.qq.com/sns/userinfo?access_token=%s&openid=%s&lang=zh_CN", accessToken, openId);
		String accessTokenStr2 = HttpClientUtil.httpGet(accessUrl2);
		JSONObject jsonObject2 = JSON.parseObject(accessTokenStr2);
		if (jsonObject2.get("errcode") != null)
			System.out.println(jsonObject.get("errcode").toString() + ":" + jsonObject.get("errmsg"));
		String nickname = jsonObject2.getString("nickname");
		String headimgurl = jsonObject2.getString("headimgurl");
		String isSnapshotuser = jsonObject.getString("is_snapshotuser");
		userInfo = "用户OpenId：" + openId + "用户昵称：" + nickname + "用户头像地址：" + headimgurl;
		System.out.println(userInfo);
		gzhWeixin.setOpenid(openId);
		gzhWeixin.setNickname(nickname);
		gzhWeixin.setHeadimgurl(headimgurl);
		gzhWeixin.setIsSnapshotuser(isSnapshotuser);
		return CommonResult.success(gzhWeixin);
	}


	@ApiOperation(value = "通过公众号验证码注册账号或登录")
	@RequestMapping(value = {"/gzh/phoneCodeLogin"}, method = RequestMethod.POST)
	@ResponseBody
	public CommonResult phoneLogin(String imeId,
								   String phoneType,
								   String registrationId,
								   String inviteCode,
								   String phone,
								   String code,
								   String gzhOpenId,
								   String unionId,
								   String gzhNickname,
								   String gzhHeadimgurl) throws ServiceException {
		//校验短信验证码
		verifyCodeService.validateCode(phone, code);
		UmsMember member = memberService.getMemberByParams(phone, MemberTypes.PHONE);
		String isRegister = "1";

		if (member == null) {
			//如果这个手机号没有注册，那么先添加注册
			isRegister = "1";
			member = new UmsMember();
			member.setGzhOpenId(gzhOpenId);
			member.setUnionid(unionId);
			member.setHeadImg(configService.getValueByNid(ConfigEnums.ConfigTypes.HEADIMG.getNid()));
			member.setNickname(DesensitizedUtil.mobilePhone(phone));

			if (StringUtils.isNotBlank(gzhNickname)){
				member.setNickname(gzhNickname);
				member.setWeixin(gzhNickname);
			}
			if (StringUtils.isNotBlank(gzhHeadimgurl)){
				member.setHeadImg(gzhHeadimgurl);
			}

			member.setPhone(phone);
			member.setCode(phone);
			member.setPhoneStatus(CommonConstant.SUS_INT);
			member.setGender("");
			member.setProvince("");
			member.setCity("");
			member.setArea("");
			member.setMethod(1);
			member.setType(CommonConstant.BUYER);
			if (StringUtils.isNotBlank(inviteCode)) {
				if ("8912058".equals(inviteCode)) {
					member.setTjrId(0);
				} else {
					SysInviteCode config = inviteCodeService.getConfigByInviteCode(inviteCode);
					if (config != null) {
						member.setTjrId(config.getUserId());
					}
				}
			}
			member.setPassword("123456");
			memberService.register(member, false);
		} else {
			//如果这个手机注册了，直接登录
			isRegister = "0";
			//登录
			if (StringUtils.isNotBlank(gzhOpenId)) {
				UmsMember updateMember = new UmsMember();
				updateMember.setId(member.getId());
				updateMember.setGzhOpenId(gzhOpenId);
				updateMember.setUnionid(unionId);
				memberService.updateMember(updateMember);
			}
		}

		//进行登录

		String token = memberService.loginByNoPassword(member.getCode());
		if (token == null) {
			throw new ServiceException("username.notfound");
		}
		memberImeIdService.loginByImeId(member, imeId, phoneType);
		if(StringUtils.isNotBlank(registrationId)){
			UmsMember updateMember = new UmsMember();
			updateMember.setId(member.getId());
			updateMember.setRegistrationId(registrationId);
			memberService.updateMember(updateMember);
		}

		Map<String, Object> tokenMap = new HashMap<>();
		tokenMap.put("token", token);
		tokenMap.put("tokenHead", tokenHead);
		UmsMember memberResult = memberService.getCurrentMember();
		tokenMap.put("member", memberResult);
		tokenMap.put("isRegister", isRegister);
		tokenMap.put("openId", gzhOpenId);
//		getCurrentMember();
		return CommonResult.success(tokenMap);

	}

}